import request from '@/api/request'

// 查询近期提交的简历（必须提供邮箱）
export async function getResumesByEmail(data: { email: string; page?: number; size?: number }) {
  if (!data?.email || !String(data.email).trim()) {
    throw new Error('email is required')
  }
  const res = await request<any>({
    url: '/counselor/apply/resumes',
    method: 'POST',
    data
  })
  
  const raw = (res as any)?.data ?? res
  // 后端返回结构示例：
  // { fileName, fileUrl, exists, userId, resumeId }
  let list: any[] = []
  if (Array.isArray(raw)) {
    list = raw.map((it) => mapResumeItem(it, data.email))
  } else if (raw && typeof raw === 'object') {
    // 兼容多种包裹结构
    if (Array.isArray((raw as any).list)) {
      list = (raw as any).list.map((it: any) => mapResumeItem(it, data.email))
    } else {
      list = [mapResumeItem(raw, data.email)]
    }
  }
  return { ...(res as any), data: { list, total: list.length } }
}

function mapResumeItem(src: any, fallbackEmail?: string) {
  console.log('mapResumeItem src:', src)
  const fileName = src?.fileName ?? src?.filename ?? null
  const fileUrl = src?.fileUrl ?? src?.url ?? null
  const exists = src?.exists ?? null
  const userId = src?.userId ?? null
  const resumeId = src?.resumeId ?? src?.id ?? null
  const email = src?.email ?? src?.userEmail ?? src?.emailAddress ?? fallbackEmail ?? null
  const username = src?.username ?? src?.userName ?? src?.nickName ?? src?.nickname ?? null
  const submittedAt = src?.submittedAt ?? src?.createdAt ?? src?.createTime ?? src?.created_at ?? src?.timestamp ?? null
  return {
    id: resumeId ?? undefined,
    resumeId,
    userId,
    fileName,
    fileUrl,
    exists,
    email,
    username,
    submittedAt,
  }
}

// 兼容旧调用名
export function listRecentResumesApi(data: { email: string; page?: number; size?: number }) {
  return getResumesByEmail(data)
}
